<!--
 * @docName: PasswordSettings.vue
 * @Author: mwl
 * @Date: 17:12
 * @LastEditors: mwl
 * @LastEditTime: 17:12
-->
<template>
  <div>
    <div class='top-title'>设定登录密码</div>
    <div class="main user-layout-register">
      <!-- <div v-if="gotoLogConfig.currentData.entName" style="font-weight: bold;font-size: 16px;">参与管理的渠道企业：{{gotoLogConfig.currentData.entName}} <a-button type="link" @click="gotoLogConfig.visible = true">更换 </a-button></div> -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item prop="phoneNo" label="登录手机号">
          <a-input v-model="model.phoneNo" size="large" placeholder="11 位手机号" />
          <span class="tips">仅支持中国大陆手机号注册</span>
        </a-form-model-item>
        <a-row>
          <a-form-model-item prop="captcha" label="验证码">
            <a-col class="gutter-row" :span="14">
              <a-input v-model="model.captcha" size="large" type="text" placeholder="验证码" autocomplete="off">
                <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
              </a-input>
            </a-col>
            <a-col class="gutter-row" :span="9" :offset="1">
              <a-button
                class="getCaptcha"
                size="large"
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="!state.smsSendBtn && '发送验证码'||(state.time+' s')"></a-button>
            </a-col>
          </a-form-model-item>
        </a-row>
        <a-form-model-item prop="password" label="设置登录密码">
          <a-input-password allow-clear
                            v-model="model.password"
                            size="large"
                            @click="handlePasswordInputClick"
                            :type="inputType" :autoComplete="autoCom" @change="changeInputType"
                            placeholder="至少9位密码，区分大小写">
          </a-input-password>
        </a-form-model-item>

        <a-form-model-item prop="password2" label="再次输入密码">
          <a-input-password allow-clear v-model="model.password2" size="large" placeholder="确认密码" :type="inputType" :autoComplete="autoCom" @change="changeInputType"></a-input-password>
        </a-form-model-item>
      </a-form-model>

    </div>
    <a-form style="max-width: 500px; margin: 40px auto 0;">
      <a-form-item :wrapperCol="{span: 19, offset: 6}">
<!--        <a-button @click="prevStep">上一步</a-button>-->
        <a-button
                  type="primary"
                  :loading="registerBtn"
                  htmlType="submit"
                  @click.stop.prevent="nextStep"
                  :disabled="registerBtn"
        >下一步</a-button>
      </a-form-item>
    </a-form>
    <settle-modal :isShow="visible" @modalHidden="modalHidden"></settle-modal>
    <!-- 强制选择要管理的企业 -->
    <a-modal v-model="gotoLogConfig.visible" :title="gotoLogConfig.title" :footer="null" :maskClosable="false">
      <a-radio-group v-model="gotoLogConfig.entID" >
        <a-radio :key="'a-radio-'+index" :style="gotoLogConfig.radioStyle" :value="item.entID" v-for="(item,index) in gotoLogConfig.entList">
          {{item.entName}}
        </a-radio>
      </a-radio-group>
      <a-button type="primary" block style="margin: 40px 0px 20px 0; " @click="addQD">
        加入该企业
      </a-button>
    </a-modal>
  </div>
</template>
<!--size="large"
type="primary"
htmlType="submit"
class="register-button"
:loading="registerBtn"
@click.stop.prevent="handleSubmit"
:disabled="registerBtn"-->
<script>
import Vue from 'vue'
import {mixinDevice} from '@/utils/mixin.js'
import { ACCESS_TOKEN, UI_CACHE_DB_DICT_DATA, USER_INFO, USER_NAME } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { getChannelRegist, getCheckLoginPhone, getSendSMSCode } from '@api/register'
import settleModal from  './settleModal'
const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a',
}
export default {
  name: "PasswordSettings",
  components: {settleModal},
  mixins: [mixinDevice],
  data () {
    return {
      gotoLogConfig:{
        stateNum:'0', // 默认值 0  输入手机后 1   变更 2
        visible:false,
        title:'选择参与管理的渠道企业',
        radioStyle: {
          display: 'block',
          height: '30px',
          lineHeight: '30px',
        },
        entID:'',
        entList:[
          { entName:'测试企业1', entID:'1'},
          { entName:'测试企业2', entID:'2'},
          { entName:'测试企业3', entID:'3'},
          { entName:'测试企业4', entID:'4'},
        ],
        // 当前所选的渠道
        currentData:{}
      },
      loading: false,
      model: {},
      modelbus:null,
      visible: false,
      labelCol: { span:6},
      wrapperCol: { span: 18 },
      validatorRules: {
        password: [
          { required: true , message: '请输入密码!' },
          { validator: this.handlePasswordLevel }
        ],
        password2: [
          { required: true , message: '请输入确认密码!' },
          { validator: this.handlePasswordCheck }
        ],
        phoneNo: [
          { required: true,message: '请输入手机号!' , trigger: 'blur'},
          { validator: this.handlePhoneCheck }
        ],
        captcha: [
          { required: true ,message: '请输入验证码!'},
          { validator: this.handleCaptchaCheck }
        ]
      },
      state: {
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false,
      radioChange: true,

      inputType:'text',
      autoCom: 'off',
    }
  },
  computed: {
    passwordLevelClass() {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName() {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor() {
      return levelColor[this.state.passwordLevel]
    }
  },
  created() {
    if(this.$route.query.phone){
      this.model.phoneNo = this.$route.query.phone
    }
  },
  mounted() {

  },
  methods: {
    /**
     * 添加渠道
     */
    addQD(){
      const tempid =  this.gotoLogConfig.entID
      if(!this.isType.isEmpty(tempid)){
        this.gotoLogConfig.entList.forEach(item => {
          if(item.entID == tempid){
           this.gotoLogConfig.currentData = item
           this.gotoLogConfig.visible = false
          }
        });
      }
      console.log(tempid,!this.isType.isEmpty(tempid),this.gotoLogConfig.currentData);
    },


    btnModelFun(){
      this.visible = true;
    },
    modalHidden(){
      this.visible = false;
    },
    //密码不自动带入浏览器保存
    changeInputType(e){
      if(e.target.value !=''){
        this.inputType = 'password'
        this.autoCom = 'new-password'
      }else{
        this.inputType = 'text'
        this.autoCom = 'off'
      }
    },
    prevStep () {
      this.$router.back()
    },
    handlePasswordLevel(rule, value, callback) {
      let level = 0
      let reg = /^(?=.*[a-zA-Z])(?=.*\d).{9,15}$/;
      if (!reg.test(value)) {
        callback(new Error('密码由9~15位数字和字母组成!'))
      }
      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        callback(new Error('密码强度不够'))
      }
    },

    handlePasswordCheck(rule, value, callback) {
      let password = this.model['password']
      //console.log('value', value)
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },
    handleCaptchaCheck(rule, value, callback){
      if(!value){
        callback(new Error("请输入验证码"))
      }else{
        callback();
      }
    },
    handlePhoneCheck(rule, value, callback) {
      let reg = /^(1\d{10})$/;
      if(!reg.test(value)){
        callback(new Error("请输入正确手机号"))
      }else{
        var params = {
          phone: value,
        };
        getCheckLoginPhone(params).then((res) => {
          console.log('************************',this)
          if (res.success) {
            // if( this.gotoLogConfig.stateNum=='0'){
            //   this.gotoLogConfig.visible = true
            //   this.gotoLogConfig.stateNum = '1'
            // }
            callback()
          } else {
            // this.gotoLogConfig.entID = ''
            // this.gotoLogConfig.currentData = {}
            let s = <p>{res.message}，请点此 <a-button type="link" onClick={this.btnModelFun} style='padding:0;color:#6d8ef2;cursor: pointer;'>申请服务</a-button>，我们将尽快与您联系！</p>
            callback(s)
          }
        })
      }
    },
    handlePasswordInputClick() {
      if (!this.isMobile()) {
        this.state.passwordLevelChecked = true
        return;
      }
      this.state.passwordLevelChecked = false
    },
    handleReserve(e){
      this.radioChange = e.target.checked;
    },
    nextStep() {
      this.$refs['form'].validate((success) => {
        if (success==true) {
          let params = {};
          params = this.model;
          getChannelRegist(params).then((res) => {
            if (!res.success) {
              this.$message.error(res.message)
            }else{
              const result = res.result
              const userInfo = result.userInfo;
              Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
              Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
              this.$store.commit('SET_TOKEN', result.token)
              this.$store.commit('SET_INFO', userInfo)
              this.$store.commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
              this.$store.commit('SET_AVATAR', userInfo.avatar)
              this.$router.push({path:'/registerProcess/registerProcess'});
            }
          }).catch(err => {});
        }
      })
    },
    getCaptcha(e) {
      e.preventDefault()
      let that = this
      this.$refs['form'].validateField(['phoneNo'], (err) => {
          if (!err) {
            this.state.smsSendBtn = true;
            let interval = window.setInterval(() => {
              if (that.state.time-- <= 0) {
                that.state.time = 60;
                that.state.smsSendBtn = false;
                window.clearInterval(interval);
              }
            }, 1000);
            const hide = this.$message.loading('验证码发送中..', 3);
            const params = {
              phone: this.model.phoneNo,
              // smsmode: "1",
              transCode:'1002'
            };
            getSendSMSCode(params).then((res) => {
              if (!res.success) {
                this.registerFailed(res.message);
                setTimeout(hide, 0);
              }
              setTimeout(hide, 500);
            }).catch(err => {
              setTimeout(hide, 1);
              clearInterval(interval);
              that.state.time = 60;
              that.state.smsSendBtn = false;
              this.requestFailed(err);
            });
          }
        }
      );
    },
    registerFailed(message) {
      this.$notification['error']({
        message: "注册失败",
        description: message,
        duration: 2,
      });

    },
    requestFailed(err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || "请求出现错误，请稍后再试",
        duration: 4,
      });
      this.registerBtn = false;
    },
  },
  watch: {
    'state.passwordLevel'(val) {
      // console.log(val)

    }
  },
}
</script>

<style lang="less" scoped>
.main{
  width: 500px;
  margin: auto;
}
.stepFormText {
  margin-bottom: 24px;

  .ant-form-item-label,
  .ant-form-item-control {
    line-height: 22px;
  }
}

</style>
<style lang="less">
.user-register {

  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #52c41a;
  }

}

.user-layout-register {
  .ant-input-group-addon:first-child {
    background-color: #fff;
  }
}
</style>
<style lang="less" scoped>
.top-title{
  max-width: 1200px;
  margin:0 auto 60px;
  font-size: 30px;
  padding: 80px 100px 24px;
  border-bottom: 1px solid #ccc;
}
.user-layout-register {

  & > h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }
  .tips{
    position: absolute;
    white-space: nowrap;
    color: #a8a8a8;
    font-size: 14px;
    margin-left: 10px;
  }
  .register-button {
    width: 50%;
  }

  .login {
    float: right;
    line-height: 40px;
  }
}
</style>
